//
//  YRSafeSaveImage.swift
//  Lottery
//
//  Created by 黄丹 on 2019/3/31.
//  Copyright © 2019 薛永伟. All rights reserved.
//

import Foundation
import Photos

/// 安全保存，直接调用即可，所有权限相关均已完成处理。
struct YRSafeSaveImage {
    
    /// 保存到相册
    static func saveImageToAlbum(image:UIImage , alertSetting: Bool = false,sucessMsg:String = "已保存到相册"){
        
        PHPhotoLibrary.requestAuthorization { (status) in
            switch status{
            case .authorized:
                PHPhotoLibrary.shared().performChanges({
                    PHAssetChangeRequest.creationRequestForAsset(from: image)
                }, completionHandler: { (finished, error) in
                    DispatchQueue.main.async {
                        if finished {
                            SVProgressHUD.showSuccess(withStatus: sucessMsg)
                        }else{
                            SVProgressHUD.showError(withStatus: error?.localizedDescription ?? "保存失败")
                        }
                    }
                })
                break
            default:
                if alertSetting {
                    DispatchQueue.main.async {
                        let alv = UIAlertController.init(title: "保存失败", message: "需要到设置里开启读写相册的权限", preferredStyle: .alert)
                        let cancle = UIAlertAction.init(title: "取消", style: .cancel, handler: nil)
                        let accept = UIAlertAction.init(title: "设置", style: .default, handler: { (action) in
                            if let settingURL = URL.init(string: UIApplication.openSettingsURLString){
                                UIApplication.shared.open(settingURL, options: [:], completionHandler: nil)
                            }
                        })
                        alv.addAction(cancle)
                        alv.addAction(accept)
                        (UIApplication.shared.delegate as! AppDelegate).window?.rootViewController?.present(alv, animated: true, completion: nil)
                    }
                }else{
                    DispatchQueue.main.async {
                        SVProgressHUD.showError(withStatus: "保存失败！")
                    }
                }
                break
            }
        }
    }
}

